package info.cs52.fes.dao;

import java.util.List;

import info.cs52.fes.Application;
import info.cs52.fes.data.Dish;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

public class DishDAO {

	public static Dish findByName(String name) {
		EntityManager em = Application.getEntityManager();
		Query query = em.createQuery("select d from Dish d where name=:name");
		query.setParameter("name", name);
		List dishes = query.getResultList();
		if (dishes.size() == 1) {
			return (Dish) dishes.get(0);
		}
		return null;
	}

	public static Dish find(String id) {
		EntityManager em = Application.getEntityManager();
		return em.find(Dish.class, id);
	}

	public static void persist(Dish dish) {
		EntityManager em = Application.getEntityManager();
		EntityTransaction tr = em.getTransaction();
		tr.begin();
		em.persist(dish);
		tr.commit();
	}

	public static void delete(String id) {
		EntityManager em = Application.getEntityManager();
		EntityTransaction tr = em.getTransaction();
		tr.begin();
		em.remove(em.getReference(Dish.class, id));
		tr.commit();
	}

}
